/**
 * 主将训练系统完整测试脚本
 * 包含登录、角色选择、主将训练测试
 */

const WebSocket = require('ws');
const http = require('http');

class CharacterTrainingTester {
  constructor() {
    this.ws = null;
    this.userId = null;
    this.token = null;
    this.selectedCharacterId = null;
    this.messageCount = 0;
  }

  async runTest() {
    try {
      console.log('🚀 开始主将训练系统完整测试...\n');

      // 步骤1: HTTP登录
      await this.httpLogin();

      // 步骤2: WebSocket连接
      await this.connectWebSocket();

      // 步骤3: 查询角色列表
      await this.getRoleList();

      // 步骤4: 选择角色
      await this.selectRole();

      // 步骤5: 测试1204指令 - 获取训练信息
      await this.testGetTrainingInfo();

      // 步骤6: 测试1205指令 - 获取训练详情
      await this.testGetTrainingDetails();

      // 步骤7: 测试1207指令 - 开始训练
      await this.testStartTraining();

      console.log('\n🎉 主将训练系统测试完成！');

    } catch (error) {
      console.error('❌ 测试失败:', error.message);
    } finally {
      if (this.ws) {
        this.ws.close();
        console.log('🔌 WebSocket连接已关闭');
      }
    }
  }

  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  async httpLogin() {
    console.log('🔐 步骤1: HTTP登录测试...');
    
    return new Promise((resolve, reject) => {
      const postData = JSON.stringify({
        mobile: '13800138000',
        pwd: 'e10adc3949ba59abbe56e057f20f883e' // 123456的MD5值
      });

      const options = {
        hostname: 'localhost',
        port: 3000,
        path: '/user-service/user/login',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(postData)
        }
      };

      const req = http.request(options, (res) => {
        let data = '';
        res.on('data', (chunk) => {
          data += chunk;
        });
        res.on('end', () => {
          try {
            const response = JSON.parse(data);
            if (response.code === 0) {
              this.userId = response.data.userId;
              this.token = response.data.accessToken;
              console.log(`✅ 登录成功: userId=${this.userId}, token=${this.token.substring(0, 10)}...`);
              resolve();
            } else {
              reject(new Error(`登录失败: ${response.msg}`));
            }
          } catch (error) {
            reject(new Error(`解析响应失败: ${error.message}`));
          }
        });
      });

      req.on('error', (error) => {
        reject(new Error(`HTTP请求失败: ${error.message}`));
      });

      req.write(postData);
      req.end();
    });
  }

  async connectWebSocket() {
    console.log('\n🔌 步骤2: WebSocket连接测试...');
    
    return new Promise((resolve, reject) => {
      const wsUrl = `ws://localhost:3000/user-service/websocket?token=${this.token}`;
      this.ws = new WebSocket(wsUrl);

      this.ws.on('open', () => {
        console.log('✅ WebSocket连接成功');
        resolve();
      });

      this.ws.on('error', (error) => {
        console.error('❌ WebSocket连接失败:', error.message);
        reject(error);
      });

      this.ws.on('message', (data) => {
        this.messageCount++;
        try {
          const message = JSON.parse(data.toString());
          console.log(`📨 收到消息 #${this.messageCount}:`, JSON.stringify(message, null, 2));
        } catch (error) {
          console.log(`📨 收到原始消息 #${this.messageCount}:`, data.toString());
        }
      });
    });
  }

  async getRoleList() {
    console.log('\n📋 步骤3: 查询角色列表...');
    
    return new Promise((resolve) => {
      const message = { c: 3 };
      this.ws.send(JSON.stringify(message));
      console.log('📤 发送消息:', message);
      
      // 等待响应
      setTimeout(() => {
        console.log('✅ 查询角色列表完成');
        resolve();
      }, 1000);
    });
  }

  async selectRole() {
    console.log('\n🎯 步骤4: 选择角色...');
    
    return new Promise((resolve) => {
      const message = { c: 4, d: { id: 2001 } };
      this.ws.send(JSON.stringify(message));
      console.log('📤 发送消息:', message);
      
      // 等待响应
      setTimeout(() => {
        this.selectedCharacterId = 2001;
        console.log('✅ 角色选择完成');
        resolve();
      }, 1000);
    });
  }

  async testGetTrainingInfo() {
    console.log('\n🏋️ 步骤5: 测试1204指令 - 获取训练信息...');
    
    return new Promise((resolve) => {
      const message = { c: 1204 };
      this.ws.send(JSON.stringify(message));
      console.log('📤 发送消息:', message);
      
      // 等待响应
      setTimeout(() => {
        console.log('✅ 1204指令测试完成');
        resolve();
      }, 2000);
    });
  }

  async testGetTrainingDetails() {
    console.log('\n📊 步骤6: 测试1205指令 - 获取训练详情...');
    
    return new Promise((resolve) => {
      const message = { c: 1205 };
      this.ws.send(JSON.stringify(message));
      console.log('📤 发送消息:', message);
      
      // 等待响应
      setTimeout(() => {
        console.log('✅ 1205指令测试完成');
        resolve();
      }, 2000);
    });
  }

  async testStartTraining() {
    console.log('\n🚀 步骤7: 测试1207指令 - 开始训练...');
    
    return new Promise((resolve) => {
      const message = { c: 1207, d: { h: 10 } };
      this.ws.send(JSON.stringify(message));
      console.log('📤 发送消息:', message);
      
      // 等待响应
      setTimeout(() => {
        console.log('✅ 1207指令测试完成');
        resolve();
      }, 2000);
    });
  }
}

// 运行测试
if (require.main === module) {
  const tester = new CharacterTrainingTester();
  tester.runTest().catch((error) => {
    console.error('💥 测试执行失败:', error.message);
    process.exit(1);
  });
}

module.exports = { CharacterTrainingTester };
